﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 13/06/2011
    /// Description: The class product controller
    /// Modified by Vietlv
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Product)]
    public class ProductController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Product/
        public ActionResult Index(int? page)
        {
            try
            {
                var action = Request["hdAction"];
                if (action != null && (action == "delete" || action == "update"))
                {
                    try
                    {
                        foreach (string key in Request.Form)
                        {
                            var checkbox = String.Empty;
                            if (key.StartsWith("chk"))
                            {
                                checkbox = Request.Form["" + key];

                                if (checkbox != "false")
                                {
                                    int strId = Utils.ParseInt(key.Substring(4));
                                    if (strId > 0)
                                    {
                                        Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == strId);
                                        if (pro != null)
                                        {
                                            if (action == "delete")
                                            {
                                                string subPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, pro.ID);
                                                string subThumbPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, "Thumb\\" + pro.ID);
                                                if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                                                {
                                                    // If it doesn't then we just create it before going any further
                                                    Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, true);
                                                }
                                                if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath))
                                                {
                                                    // If it doesn't then we just create it before going any further
                                                    Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath, true);
                                                }
                                                eDataContext.CommentsInProducts.DeleteAllOnSubmit(from e in eDataContext.CommentsInProducts where e.ProductID == strId select e);
                                                eDataContext.Products.DeleteOnSubmit(pro);
                                                eDataContext.SubmitChanges();
                                            }
                                            else
                                            {
                                                pro.ModDate = DateTime.Now;
                                                eDataContext.SubmitChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exp)
                    {
                        ViewData[Messages.MessageInfo] = exp.Message;
                        return View();
                    }
                }
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("report.PageNumber", "page", 1));
                var pageIndex = pageNumber - 1;
                string order = UserState.getUserStateFromRequest("product.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
                var typeID = Convert.ToInt32(UserState.getUserStateFromRequest("product.ProductType", "TypeID", 0)); // Inserted by Vietlv (26/07/2011)
                int catID = Convert.ToInt32(UserState.getUserStateFromRequest("product.CatID", "CatID", 0));
                var holidayID = Convert.ToInt32(UserState.getUserStateFromRequest("product.Holiday", "HolidayID", 0));
                string keyword = UserState.getUserStateFromRequest("product.Keyword", "Keyword", "").ToString();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("product.pageSize", "PageSize", 20).ToString());

                var isAdmin = UserManager.CheckRole(RoleSystem.Administrator);

                var pros = ProductManager.GetList(typeID, catID, holidayID, 0,0, 0,
                    keyword, 0, 0, 0, 0, 0, 0, order, orderDir, pageIndex, pageSize);


                List<ProductCategory> categories = eDataContext.ProductCategories
                                                .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                .ToList();

                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;
                var listProductTypes = eDataContext.ProductTypes.ToList();
                return View(new ProductViewModel
                {
                    Products = pros,
                    Categories = categories,
                    ProductHolidays = eDataContext.ProductHolidays.ToList(),
                    FilterCategoryID = catID,
                    FilterProductHolidayID = holidayID,
                    FilterProductTypeID = typeID,
                    Keyword = keyword,
                    ProductTypes = listProductTypes,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Product/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                // product detail
                Product pro = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();

                // product category
                List<ProductCategory> categories = eDataContext.ProductCategories
                                                .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                .ToList();
                List<string> listF = pro.AddDate != null ? Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.DocumentInArticleRootPath, Settings.Default.ProductFormatSubPath, pro.AddDate.Value) : null; // Modified by Vietlv (isert confident pro.AddDate = null)
                // List Direction

                return View(new ProductInputModel
                {
                    Categories = categories,
                    Product = pro,
                    ListFile = listF,
                    ImageRootUrl = Settings.Default.SiteRootUrl+Settings.Default.ProductRootUrl
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Product/Create
        public ActionResult Create()
        {
            try
            {
                ProductInputModel p = new ProductInputModel();
                p.Categories = eDataContext.ProductCategories.ToList();
                p.Events = eDataContext.Events.ToList();
                p.Insurers = eDataContext.Insurers.ToList();
                p.Manufacturers = eDataContext.Manufacturers.ToList();
                p.Providers = eDataContext.Providers.ToList();
                p.ProductHolidays = eDataContext.ProductHolidays.ToList();
                p.ProductTypes = eDataContext.ProductTypes.ToList();
                p.Countries = eDataContext.Countries.ToList();
                p.ProductExpires =Utils.StringToDictionaryIntString(Settings.Default.ProducExpire, ",");
                return View(p);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Product/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ProductInputModel m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UpdateModel(m);

                    m.Product.AddBy = UserManager.GetUserId();
                    m.Product.AddDate = DateTime.Now;
                    m.Product.ModBy = UserManager.GetUserId();
                    m.Product.ModDate = DateTime.Now;
                    
                    
                    m.Product.CatID = Utils.ParseInt(Request["ddlCategory"]);
                    m.Product.CountryID = Utils.ParseInt(Request["ddlCountry"]) > 0 ? 
                        Utils.ParseInt(Request["ddlCountry"]) : (int?)null;
                    m.Product.ProviderID = Utils.ParseInt(Request["ddlProvider"]) > 0 ?
                        Utils.ParseInt(Request["ddlProvider"]) : (int?)null;
                    m.Product.ManufactureID = Utils.ParseInt(Request["ddlManufacturer"]) > 0 ?
                        Utils.ParseInt(Request["ddlManufacturer"]) : (int?)null;
                    m.Product.InsurerID = Utils.ParseInt(Request["ddlInsurer"]) > 0 ?
                        Utils.ParseInt(Request["ddlInsurer"]) : (int?)null;

                    m.Product.BuyUnitPrice = Utils.ParseDecimal(Request["txtBuyUnitPrice"]);

                    m.Product.BuyTotalPrice = m.Product.BuyQuantity != null && m.Product.BuyUnitPrice != null ?
                        m.Product.BuyQuantity * m.Product.BuyUnitPrice : (decimal?)null;

                    m.Product.UnitPrice = Utils.ParseDecimal(Request["txtUnitPrice"]);
                    m.Product.UnitOldPrice = Utils.ParseDecimal(Request["txtUnitOldPrice"]);
                    m.Product.DiscountValue = Utils.ParseDecimal(Request["txtDiscountValue"]);
                    m.Product.DiscountPercent = Utils.ParseDecimal(Request["txtDiscountPercent"]);
                    
                    m.Product.ConvertPrice = GetConvertPrice(m.Product.UnitPrice.Value);

                    m.Product.FreeShipping = Utils.ParseDouble(Request["txtShipping"]) >= 0 ? Utils.ParseDouble(Request["txtShipping"]) : (double?)null;
                    
                    m.Product.BeginDate =Request["txtFromDate"] !=null && Request["txtFromDate"] != string.Empty ?
                        Utils.ParseDateTime(Request["txtFromDate"], new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                    var times =Utils.ParseInt(Request["ddlExpireDate"]);
                    m.Product.EndDate = DateTime.Now.AddDays(times);
                    if (m.Product.BeginDate != null && m.Product.EndDate != null && m.Product.MinVoucher != null)
                    {
                        m.Product.DealYN = true;
                    }
                    else m.Product.DealYN = false;

                    if (m.Product.MetaKeyword == null || m.Product.MetaKeyword == string.Empty) m.Product.MetaKeyword = m.Product.Name;
                    if (m.Product.MetaDescription == null || m.Product.MetaDescription == string.Empty) m.Product.MetaDescription = m.Product.Name;
                    if (m.Product.MetaTag == null || m.Product.MetaTag == string.Empty) m.Product.MetaTag = m.Product.Name;
                    eDataContext.Products.InsertOnSubmit(m.Product);
                    eDataContext.SubmitChanges();
                    try
                    {
                        #region Loai san pham
                        var listId = new List<int>();
                        var arrTypeID = Request["chkType"].Split(',');
                        foreach (string key in arrTypeID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listId.Add(strId);
                                }
                            }
                        }
                        if (listId.Count > 0)
                        {
                            foreach (var id in listId) {
                                ProductTypeMap map = new ProductTypeMap();
                                map.ProductID = m.Product.ID;
                                map.TypeID = id;
                                eDataContext.ProductTypeMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Ngay le
                        var listHolidayId = new List<int>();
                        var arrHoliID = Request["chkHoliday"].Split(',');
                        foreach (string key in arrHoliID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listHolidayId.Add(strId);
                                }
                            }
                        }
                        if (listHolidayId.Count > 0)
                        {
                            foreach (var id in listHolidayId)
                            {
                                ProductHolidayMap map = new ProductHolidayMap();
                                map.ProductID = m.Product.ID;
                                map.HolidayID = id;
                                eDataContext.ProductHolidayMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Su kien
                        var listEventId = new List<int>();
                        var arrEventID = Request["chkEvent"].Split(',');
                        foreach (string key in arrEventID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listEventId.Add(strId);
                                }
                            }
                        }
                        if (listEventId.Count > 0)
                        {
                            foreach (var id in listEventId)
                            {
                                ProductEventMap map = new ProductEventMap();
                                map.ProductID = m.Product.ID;
                                map.EventID = id;

                                eDataContext.ProductEventMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Tag
                        var articleTageName = Request["TagName"] != null ? Request["TagName"].ToString() : string.Empty;
                        if (articleTageName.Length > 0)
                        {
                            var listTagName = articleTageName.Split(',');
                            if (listTagName.Length > 0)
                            {
                                for (int i = 0; i < listTagName.Length; i++)
                                {
                                    var itemTagName = listTagName[i].ToString();
                                    if (itemTagName.Trim().Length > 0)
                                    {
                                        var countTag = eDataContext.Tags
                                                        .Where(e => e.Keyword.Trim().ToLower().
                                                            Contains(itemTagName.Trim().ToLower()))
                                                            .FirstOrDefault();
                                        // Case tag exist in database
                                        if (countTag != null)
                                        {
                                            ProductTagMap map = new ProductTagMap();
                                            map.ProductID = m.Product.ID;
                                            map.TagID = countTag.ID;
                                            eDataContext.ProductTagMaps.InsertOnSubmit(map);
                                            eDataContext.SubmitChanges();
                                        }
                                        else // Case tag don't exist
                                        {
                                            // Create new Tags
                                            Tag newTag = new Tag();
                                            newTag.Keyword = itemTagName.Trim();
                                            newTag.AddBy = UserManager.GetUserId();
                                            newTag.AddDate = DateTime.Now;
                                            eDataContext.Tags.InsertOnSubmit(newTag);
                                            eDataContext.SubmitChanges();
                                            // Create new ArticleTagmap
                                            ProductTagMap map = new ProductTagMap();
                                            map.ProductID = m.Product.ID;
                                            map.TagID = countTag.ID;
                                            eDataContext.ProductTagMaps.InsertOnSubmit(map);
                                            eDataContext.SubmitChanges();
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    catch (Exception exp)
                    {
                        ViewData[Messages.MessageInfo] = exp.Message;
                        return View();
                    }
                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                        eDataContext.SubmitChanges();
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                    }
                    eDataContext.SubmitChanges();
                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ImagePaths")
                        {
                            string filePath = string.Empty;
                            string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                            file.SaveAs(filePath);
                        }
                    }
                    #endregion

                    return RedirectToAction("Index");
                }
                else
                {
                    throw new Exception("Dữ liệu nhập không đúng.");
                }
            }
            catch (Exception exp)
            {                
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        



        #region GET: /Product/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {

                ProductInputModel p = new ProductInputModel();
                p.Categories = eDataContext.ProductCategories.ToList();
                p.Events = eDataContext.Events.ToList();
                p.Insurers = eDataContext.Insurers.ToList();
                p.Manufacturers = eDataContext.Manufacturers.ToList();
                p.Providers = eDataContext.Providers.ToList();
                p.ProductHolidays = eDataContext.ProductHolidays.ToList();
                p.ProductTypes = eDataContext.ProductTypes.ToList();
                p.Countries = eDataContext.Countries.ToList();
                p.Product = eDataContext.Products.Where(e => e.ID == id).FirstOrDefault();
                p.ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootPath;
                p.ImageRootUrls = Settings.Default.SiteRootUrl;
                p.ListFile = Uploads.GetFile(id, Settings.Default.SiteRootPath,
                    Settings.Default.ProductRootPath, Settings.Default.ProductFormatSubPath, p.Product.AddDate.Value);
                p.ProductExpires = Utils.StringToDictionaryIntString(Settings.Default.ProducExpire, ",");
                return View(p);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Product/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ProductInputModel m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    m.Product = eDataContext.Products.Where(e => e.ID == id).SingleOrDefault();
                    UpdateModel(m);
                    m.Product.ModBy = UserManager.GetUserId();
                    m.Product.ModDate = DateTime.Now;

                    
                    m.Product.CatID = Utils.ParseInt(Request["ddlCategory"]);
                    m.Product.CountryID = Utils.ParseInt(Request["ddlCountry"]) > 0 ?
                        Utils.ParseInt(Request["ddlCountry"]) : (int?)null;
                    m.Product.ProviderID = Utils.ParseInt(Request["ddlProvider"]) > 0 ?
                        Utils.ParseInt(Request["ddlProvider"]) : (int?)null;
                    m.Product.ManufactureID = Utils.ParseInt(Request["ddlManufacturer"]) > 0 ?
                        Utils.ParseInt(Request["ddlManufacturer"]) : (int?)null;
                    m.Product.InsurerID = Utils.ParseInt(Request["ddlInsurer"]) > 0 ?
                        Utils.ParseInt(Request["ddlInsurer"]) : (int?)null;

                    m.Product.BuyUnitPrice = Utils.ParseDecimal(Request["txtBuyUnitPrice"]);

                    m.Product.BuyTotalPrice = m.Product.BuyQuantity != null && m.Product.BuyUnitPrice != null ?
                        m.Product.BuyQuantity * m.Product.BuyUnitPrice : (decimal?)null;
                    
                    m.Product.UnitPrice = Utils.ParseDecimal(Request["txtUnitPrice"]);
                    m.Product.UnitOldPrice = Utils.ParseDecimal(Request["txtUnitOldPrice"]);
                    m.Product.DiscountValue = Utils.ParseDecimal(Request["txtDiscountValue"]);
                    m.Product.DiscountPercent = Utils.ParseDecimal(Request["txtDiscountPercent"]);

                    m.Product.ConvertPrice = GetConvertPrice(m.Product.UnitPrice.Value);
                    
                    m.Product.FreeShipping = Utils.ParseDouble(Request["txtShipping"]) >= 0 ? Utils.ParseDouble(Request["txtShipping"]) : (double?)null;

                    m.Product.BeginDate = Request["txtFromDate"] != null && Request["txtFromDate"] != string.Empty ?
                        Utils.ParseDateTime(Request["txtFromDate"], new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
                    var times = Utils.ParseInt(Request["ddlExpireDate"]);
                    m.Product.EndDate =times>0 && m.Product.BeginDate.HasValue && m.Product.EndDate.HasValue && m.Product.BeginDate<=m.Product.EndDate ? 
                        m.Product.EndDate.Value.AddDays(times) : (m.Product.BeginDate.HasValue && times>0 ? m.Product.BeginDate.Value.AddDays(times):(DateTime?)null);
                    
                    if (m.Product.BeginDate != null && m.Product.EndDate != null && m.Product.MinVoucher != null)
                    {
                        m.Product.DealYN = true;
                    }
                    else m.Product.DealYN = false;

                    if (m.Product.MetaKeyword == null || m.Product.MetaKeyword == string.Empty) m.Product.MetaKeyword = m.Product.Name;
                    if (m.Product.MetaDescription == null || m.Product.MetaDescription == string.Empty) m.Product.MetaDescription = m.Product.Name;
                    if (m.Product.MetaTag == null || m.Product.MetaTag == string.Empty) m.Product.MetaTag = m.Product.Name;
                    eDataContext.SubmitChanges();
                    try
                    {
                        eDataContext.ProductTagMaps.DeleteAllOnSubmit(m.Product.ProductTagMaps);
                        eDataContext.ProductEventMaps.DeleteAllOnSubmit(m.Product.ProductEventMaps);
                        eDataContext.ProductTypeMaps.DeleteAllOnSubmit(m.Product.ProductTypeMaps);
                        eDataContext.ProductHolidayMaps.DeleteAllOnSubmit(m.Product.ProductHolidayMaps);
                        eDataContext.SubmitChanges();
                        #region Loai doi tuong
                        var listId = new List<int>();
                        var arrTypeID = Request["chkType"].Split(',');
                        foreach (string key in arrTypeID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listId.Add(strId);
                                }
                            }
                        }
                        if (listId.Count > 0)
                        {
                            foreach (var tid in listId)
                            {
                                ProductTypeMap map = new ProductTypeMap();
                                map.ProductID = m.Product.ID;
                                map.TypeID = tid;
                                eDataContext.ProductTypeMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Ngay le
                        var listHolidayId = new List<int>();
                        var arrHoliID = Request["chkHoliday"].Split(',');
                        foreach (string key in arrHoliID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listHolidayId.Add(strId);
                                }
                            }
                        }
                        if (listHolidayId.Count > 0)
                        {
                            foreach (var hid in listHolidayId)
                            {
                                ProductHolidayMap map = new ProductHolidayMap();
                                map.ProductID = m.Product.ID;
                                map.HolidayID = hid;
                                eDataContext.ProductHolidayMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Su kien
                        var listEventId = new List<int>();
                        var arrEventID = Request["chkEvent"].Split(',');
                        foreach (string key in arrEventID)
                        {
                            if (key != "false")
                            {
                                int strId = Utils.ParseInt(key);
                                if (strId > 0)
                                {
                                    listEventId.Add(strId);
                                }
                            }
                        }
                        if (listEventId.Count > 0)
                        {
                            foreach (var eid in listEventId)
                            {
                                ProductEventMap map = new ProductEventMap();
                                map.ProductID = m.Product.ID;
                                map.EventID = eid;

                                eDataContext.ProductEventMaps.InsertOnSubmit(map);
                            }
                            eDataContext.SubmitChanges();
                        }
                        #endregion
                        #region Tag
                        var articleTageName = Request["TagName"] != null ? Request["TagName"].ToString() : string.Empty;
                        if (articleTageName.Length > 0)
                        {
                            var listTagName = articleTageName.Split(',');
                            if (listTagName.Length > 0)
                            {
                                for (int i = 0; i < listTagName.Length; i++)
                                {
                                    var itemTagName = listTagName[i].ToString();
                                    if (itemTagName.Trim().Length > 0)
                                    {
                                        var countTag = eDataContext.Tags
                                                        .Where(e => e.Keyword.Trim().ToLower().
                                                            Contains(itemTagName.Trim().ToLower()))
                                                            .FirstOrDefault();
                                        // Case tag exist in database
                                        if (countTag != null)
                                        {
                                            ProductTagMap map = new ProductTagMap();
                                            map.ProductID = m.Product.ID;
                                            map.TagID = countTag.ID;
                                            eDataContext.ProductTagMaps.InsertOnSubmit(map);
                                            eDataContext.SubmitChanges();
                                        }
                                        else // Case tag don't exist
                                        {
                                            // Create new Tags
                                            Tag newTag = new Tag();
                                            newTag.Keyword = itemTagName.Trim();
                                            newTag.AddBy = UserManager.GetUserId();
                                            newTag.AddDate = DateTime.Now;
                                            eDataContext.Tags.InsertOnSubmit(newTag);
                                            eDataContext.SubmitChanges();
                                            // Create new ArticleTagmap
                                            ProductTagMap map = new ProductTagMap();
                                            map.ProductID = m.Product.ID;
                                            map.TagID = countTag.ID;
                                            eDataContext.ProductTagMaps.InsertOnSubmit(map);
                                            eDataContext.SubmitChanges();
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    catch (Exception exp)
                    {
                        ViewData[Messages.MessageInfo] = exp.Message;
                        return View();
                    }
                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                        eDataContext.SubmitChanges();
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                    }
                    eDataContext.SubmitChanges();
                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ImagePaths")
                        {
                            string filePath = string.Empty;
                            string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                            file.SaveAs(filePath);
                        }
                    }
                    #endregion

                    return RedirectToAction("Index");
                }
                else
                {
                    throw new Exception("Dữ liệu nhập không đúng.");
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        public ActionResult DelImg(int id)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id);
                if (pro != null && pro.ImagePath != null)
                {
                    string filePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + pro.ID + "_" + pro.ImagePath;
                    Uploads.DeleteFile(filePath);
                    pro.ImagePath = null;
                    eDataContext.SubmitChanges();
                    return RedirectToAction("Edit", new { id = pro.ID });
                }
                else
                {
                    return RedirectToAction("index", "home");
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        public ActionResult DeleteImg(int id)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id && e.AddBy == UserManager.GetUserId());
                string filePath = string.Empty;
                string subPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, pro.ID);
                filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, Request["img"]);
                Uploads.DeleteFile(filePath);
                return RedirectToAction("Edit", new { id = pro.ID });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message + exp.StackTrace;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Delete/5


        public ActionResult Delete(int id)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id);

                return View(pro);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Article/Delete/5

        [HttpPost]
        [Authorize()]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id);
                if (pro != null)
                {
                    string subPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, pro.ID);
                    string subThumbPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, "Thumb\\" + pro.ID);
                    if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                    {
                        // If it doesn't then we just create it before going any further
                        Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, true);
                    }
                    if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath))
                    {
                        // If it doesn't then we just create it before going any further
                        Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath, true);
                    }
                    eDataContext.ProductEventMaps.DeleteAllOnSubmit(from e in eDataContext.ProductEventMaps where e.ProductID == id select e);
                    eDataContext.ProductHolidayMaps.DeleteAllOnSubmit(from e in eDataContext.ProductHolidayMaps where e.ProductID == id select e);
                    eDataContext.ProductTypeMaps.DeleteAllOnSubmit(from e in eDataContext.ProductTypeMaps where e.ProductID == id select e);
                    eDataContext.CommentsInProducts.DeleteAllOnSubmit(from e in eDataContext.CommentsInProducts where e.ProductID == id select e);
                    eDataContext.Products.DeleteOnSubmit(pro);
                    eDataContext.SubmitChanges();
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
    }
}
